#!/bin/bash

# Instruction： https://blog.csdn.net/mzy2364/article/details/113364250

cp ~/workspace/uboot-imx/u-boot-dtb.imx ./
cp ~/workspace/linux-imx/arch/arm/boot/zImage ./
cp ~/workspace/linux-imx/arch/arm/boot/dts/imx6ull-14x14-evk.dtb ./

mkdir boot
mkdir root

dd if=/dev/zero of=imx6ull.img bs=512 count=2097152

sudo parted imx6ull.img --script -- mklabel msdos
sudo parted imx6ull.img --script -- mkpart primary fat32 20480s 1044479s
sudo parted imx6ull.img --script -- mkpart primary ext4 1228800s -1

# 获取映射到的循环设备路径
LOOP_DEVICE=$(sudo losetup -f --show imx6ull.img)
echo "Image mapped to: $LOOP_DEVICE"

sudo kpartx -va $LOOP_DEVICE

# 获取分区设备路径,重点是这个sed命令的用法
PART_DEVICE=$(echo $LOOP_DEVICE | sed 's/^\/dev\/loop/dev\/mapper\/loop/')
PART1=/${PART_DEVICE}p1
PART2=/${PART_DEVICE}p2

sudo mkfs.vfat $PART1
sudo mkfs.ext4 $PART2

sudo mount $PART1 ./boot/
sudo mount $PART2 ./root/

sudo dd if=u-boot-dtb.imx of=$LOOP_DEVICE bs=512 seek=2 conv=fsync

sudo cp zImage imx6ull-14x14-evk.dtb ./boot/

#这里需要把跟文件系统直接解压缩到./root下
sudo tar -xvf ./rootfs.tar.gz -C ./root/

sudo umount ./boot ./root
sudo kpartx -d $LOOP_DEVICE
sudo losetup -d $LOOP_DEVICE